package CompBlast;

use strict;
use Bio::Perl;
use Bio::Seq;
use Bio::Tools::Run::RemoteBlast;

sub new {
	my ($class,$limit,@keyword) = @_;

	my @params = (
		'-prog' => 'blastn',
		'-data' => 'nr',
		'-expect' => '1e-10',
		'-readmethod' => 'SearchIO');	
	my $fac = Bio::Tools::Run::RemoteBlast->new(@params);

	my $self = {};
	$self->{genus} = [@keyword];
	$self->{factory} = $fac;
	$self->{limit} = $limit;
	$self->{info} = undef;

	bless $self, $class;
	return $self;
}


sub Check {
	my ($self,$seq, $all, $v) = @_;
	
	print "\tRunning blast" if($v > 0);
	my $LIMIT = $self->{limit};
	$|++;
	my $factory = $self->{factory};
	my $r = $factory->submit_blast($seq);
	my @rhits = GetHits($r,$factory,$LIMIT,$v);
	my $g = $self->{genus};
	my @keywords = @$g;#GetKeywords();
	my $total = ($#rhits + 1);
	if($total == 0){
		print "done!\n" if($v > 0);	
		return ([$seq->id,-1],-1); 
	}
	$total = $total * ($#keywords + 1) if($all == 0);
	my $count = 0;	
	print "done!\n\tChecking for keywords" if($v > 0);
	$|++;
	foreach (@rhits){
		$count = $count + Compare($_,$all,@keywords);
	}

	print "done!\n" if($v > 0);

	return ([$seq->id,$rhits[0]] ,$count/$total*100);
}

sub Compare {
	my ($desc,$all,@keywords) = @_;
	my $count = 1;
	$count-- if($all == 0);

	L: foreach(@keywords){
		foreach(@$_){
			my $found = $desc =~ m/$_/i;
			if($found > 0){
				$count++;
				next L;
			}
		}
		return 0;
	}
	return $count;
}

sub GetHits {
	my ($r,$factory,$LIMIT,$v) = @_;
	my @rhits = ();

    while ( my @rids = $factory->each_rid ) {
      foreach my $rid ( @rids ) {
        my $rc = $factory->retrieve_blast($rid);
        if( !ref($rc) ) {
          if( $rc < 0 ) {
            $factory->remove_rid($rid);
          }
          print "." if($v > 0); 
          sleep 1;
        } else {
          my $result = $rc->next_result();
          #save the output
          #my $filename = $result->query_name()."\.out";
          #$factory->save_output($filename);
          $factory->remove_rid($rid);
          #print "\nQuery Name: ", $result->query_name(), "\n" if ($v > 0);
	  my $count = 0;
          while ( (my $hit = $result->next_hit) && $count < $LIMIT) {
	    $count++;
          #  print "\thit name is ", $hit->name, "\n" if ($v > 0);
	    my $hit_name = $hit->name;
	    #if($hit_name =~ m/gb\|(.*)\|/){
	#	push @rhits, $1;
	#    } else {
	        push @rhits, $hit->description;#$hit->name;
	 #   }
            while( (my $hsp = $hit->next_hsp) && $v > 0) {
              print "\t\tscore is ", $hsp->score, "\n" if($v > 0);
            }
          }
        }
      }
    }
	return @rhits;
  }

sub GetKeywords {
	my ($self) = @_;
	my $g = $self->{genus};
	return @$g;
}

1;
